797D - Broken BST - CodeForces Solution


data structures dfs and similar *2100

Please click on ads to support us..

C++ Code:

// https://codeforces.com/contest/797/problem/D
#include <bits/stdc++.h>
using namespace std;

int vals[100005];
pair<int, int> children[100005];
map<int, int> occ;
map<int, bool> works;

void dfs(int index, int left, int right) {
  if (left < vals[index] && vals[index] < right) {
    works[vals[index]] = true;
  }
  if (children[index].first != -2) {
    dfs(children[index].first, left, min(right, vals[index]));
  }
  if (children[index].second != -2) {
    dfs(children[index].second, max(left, vals[index]), right);
  }
}

int main() {
  cin.tie(NULL)->sync_with_stdio(false);
  int n;
  cin >> n;

  for (int i = 0; i < n; i++) {
    cin >> vals[i] >> children[i].first >> children[i].second; 
    occ[vals[i]]++;
    works[vals[i]] = false;
    children[i].first--;
    children[i].second--;
  }

  // find root
  int root = 0;
  bool root_poss[n] = {};
  for (int i = 0; i < n; i++) {
    if (children[i].first != -2) root_poss[children[i].first] = true;
    if (children[i].second != -2) root_poss[children[i].second] = true;
  }
  for (int i = 0; i < n; i++) if (root_poss[i] == false) root = i;

  // dfs, keep track of range of vals
  dfs(root, -2, 1000000001);

  int out = 0;
  for (auto thing : works) {
    if (!thing.second) out += occ[thing.first];
  }
  cout << out;
}


Comments

Submit
0 Comments
More Questions

1325D - Ehab the Xorcist
552B - Vanya and Books
1722E - Counting Rectangles
168A - Wizards and Demonstration
168B - Wizards and Minimal Spell
7A - Kalevitch and Chess
912B - New Year's Eve
1537C - Challenging Cliffs
879B - Table Tennis
1674E - Breaking the Wall
1282A - Temporarily unavailable
1366C - Palindromic Paths
336A - Vasily the Bear and Triangle
926A - 2-3-numbers
276D - Little Girl and Maximum XOR
1253C - Sweets Eating
1047A - Little C Loves 3 I
758D - Ability To Convert
733A - Grasshopper And the String
216A - Tiling with Hexagons
1351B - Square
1225A - Forgetting Things
1717A - Madoka and Strange Thoughts
1717B - Madoka and Underground Competitions
61B - Hard Work
959B - Mahmoud and Ehab and the message
802G - Fake News (easy)
1717C - Madoka and Formal Statement
420A - Start Up
1031A - Golden Plate